import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
import { stringify } from 'querystring';

declare var $: any;
@Component({
	selector: 'sa-car-bind',
	templateUrl: './car-bind.component.html',
})
export class CarBindComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	tableParam: any = {
		// phone: '',
		searchKey: '',
		carNumber: '',
		deviceId: '',
		startTime: '',
		endTime: ''
	}
	// 编辑的车辆对象
	rowContent:any = {};
	isShowDelete=false; // 默认不显示删除按钮
	// 绑定车辆列表的验证
	bindCarvalidatorOptions={
		excluded:[":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumberInput: {
				trigger:"change",
				validators: {
					notEmpty: {
						message: '请选择要绑定的车牌号'
					}
				}
			},
		}
	} 
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	ngOnInit() {
		this.initBtn();
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.select2Car(); //初始化select 2 车辆
			});
		})
		this.load();
	}
	//初始化权限按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_wx:bind:carBind')));
		if(!btnData) {
			return
		};
		for(let item of btnData) {
			if(item.sourceKey === "wx-bind:car-bind:deleteBtn" && item.parentId) {
				this.isShowDelete = true;
			}
		
		}
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	tableSearch() {
		this.curPage = 1;
		this.load();
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//初始化加载list数据
	load() {
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				// phone: this.tableParam.phone,
				carNumber: this.tableParam.carNumber,
				startTime: this.tableParam.startTime,
				endTime: this.tableParam.endTime,
				searchKey: common.stringTrim(this.tableParam.searchKey)
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("appointmentRepairCar/carBandingList.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//拉取车辆数据
	select2Car() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function (params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.tableParam.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.tableParam.carNumber = data.text.split('[')[0];
			} else {
				that.tableParam.carNumber = data.text;
			}
		});
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) { return state.text };
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.tableParam.startTime = time.startTime;
		this.tableParam.endTime = time.endTime;
	}
	del_carNumber() {
		this.tableParam.carNumber = '';
		this.tableParam.deviceId = '';
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title", "");
		$("#select2-carNumberSelect2-container").prepend(str);
	}
	// 删除车辆绑定列记录
	deleteRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let parameters = {
				ids: row.id,
				type: "1",
			}
			this.jsonApiService.http_obj("appointmentRepairCar/batchDeleted.html", parameters).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}
	// 车辆解绑
	unBindCar(row){
		this.jsonApiService.confirm_message("确认解绑该车辆么?").then(() => {
			let id = row.id;
			let parameters ={
				id :id
			}
			this.jsonApiService.http_obj("appointmentRepairCar/unBandingCar.html", parameters).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
		
	}
	// 编辑  绑定另一个车牌弹框
	updateRow(row,modal){
		modal.show();
		this.initCar(row)
		this.rowContent = JSON.parse(JSON.stringify(row));
		$("#carNumberInput").val(row.carNumber);
		$("#select2-carNumberListSelect2-container").attr("title",row.carNumber);
		$("#select2-carNumberListSelect2-container").text(row.carNumber);
		$("#bindCarFrom").data("bootstrapValidator").resetForm();
		// $("#carNumberListSelect2").select2('val',row.deviceId)
	}
	// 弹框关闭
	itemModalClose(modal){
		$("#bindCarFrom").data("bootstrapValidator").resetForm();
		modal.hide();
	}
	//清除车辆选中值
	del_carNumber2(){
		this.rowContent.deviceId = '';
		this.rowContent.carNumber = '';
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberInput').val("").change();
		$('#carNumberListSelect2').val("");
		$("#select2-carNumberListSelect2-container").empty();
		$("#select2-carNumberListSelect2-container").attr("title","");
		$("#select2-carNumberListSelect2-container").prepend(str);
	}
	//初始化车辆
	initCar(row) {
		var that = this;
		let init = $("#carNumberListSelect2").select2({
            language : "zh-CN",
            minimumInputLength: 2,
			allowClear: true,
			placeholder:"请选择",
			ajax: {
	    		url: config.BaseURL+"stats/carListByCarNumber.html",
	    		dataType: 'json',
	    		delay: 100,
	    		method: "POST",
	    		xhrFields: {withCredentials: true},
	    		data: function (params){return {"carNumber" :  params.term};},
	    		processResults: function (data, params){
					var options = new Array();
					var carNumberArr = [];
					var sameCarArr = [];
					for (let index = 0; index < data.data.length; index++) {
						let car = data.data[index];
						if(carNumberArr.indexOf(car.carNumber)!=-1){
							sameCarArr.push(car.carNumber)
						}else{
							carNumberArr.push(car.carNumber)
						}
					}
	    		    $(data.data).each(function(index, car){
						if(sameCarArr.indexOf(car.carNumber)!=-1){
							options.push({id : car.deviceId,text : car.carNumber+"["+car.parentName+"]"});
						}else{
							options.push({id : car.deviceId,text : car.carNumber});
						}
	    		    });
	    		    return {results : options};
	    		},
	    		cache: true
	        },
            templateResult : function (state){
            	if (!state.id) {return state.text;}
                var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
                return $state;
            },
       }).on("select2:select", function (e){
			var data = e.params.data;
			that.rowContent.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
				that.rowContent.carNumber = data.text.split('[')[0];
			} else {
				that.rowContent.carNumber = data.text;
			}
			// that.rowContent.carNumber = data.text.split("[")[0];
			$("#carNumberInput").val(that.rowContent.carNumber).change();
        });
		init.val(row.deviceId).trigger("change");    
	} 
	// 编辑 提交
	itemModalSubmit(modal){
		$('#bindCarFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#bindCarFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			let parameters = {
				id:this.rowContent.id,
				deviceId:this.rowContent.deviceId,
				carNumber:this.rowContent.carNumber
			}
			this.jsonApiService.http_obj("appointmentRepairCar/updateBandingCar.html", parameters).subscribe(data => {
				this.jsonApiService.message(data.message);
				modal.hide()
				this.load();
			})
		}
	}
}